package com.zscat.mallplus.center.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.TimeZone;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zscat.mallplus.active.service.ISysStoreService;
import com.zscat.mallplus.annotation.IgnoreAuth;
import com.zscat.mallplus.center.entity.CenterInviteRecords;
import com.zscat.mallplus.center.entity.CenterItem;
import com.zscat.mallplus.center.entity.CenterJifen;
import com.zscat.mallplus.center.entity.CenterVerification;
import com.zscat.mallplus.center.mapper.CenterOrderMapper;
import com.zscat.mallplus.center.mapper.CenterVerificationMapper;
import com.zscat.mallplus.center.service.CenterService;
import com.zscat.mallplus.center.service.ICenterItemService;
import com.zscat.mallplus.center.service.ICenterJifenService;
import com.zscat.mallplus.center.service.ICenterOrderService;
import com.zscat.mallplus.center.vo.IncomeDetails;
import com.zscat.mallplus.center.vo.MemberInfoVo;
import com.zscat.mallplus.cms.entity.CmsSubjectComment;
import com.zscat.mallplus.component.UserUtils;
import com.zscat.mallplus.enums.AllEnum;
import com.zscat.mallplus.enums.AllEnum.OrderType;
import com.zscat.mallplus.exception.ApiMallPlusException;
import com.zscat.mallplus.fenxiao.entity.FenxiaoMemberTotal;
import com.zscat.mallplus.fenxiao.entity.FenxiaoRecords;
import com.zscat.mallplus.fenxiao.entity.FenxiaoUserRelate;
import com.zscat.mallplus.fenxiao.mapper.FenxiaoRecordsMapper;
import com.zscat.mallplus.fenxiao.mapper.FenxiaoUserRelateMapper;
import com.zscat.mallplus.oms.entity.OmsOrder;
import com.zscat.mallplus.oms.entity.OmsOrderItem;
import com.zscat.mallplus.oms.entity.OmsOrderItemTicket;
import com.zscat.mallplus.oms.mapper.OmsOrderItemMapper;
import com.zscat.mallplus.oms.mapper.OmsOrderMapper;
import com.zscat.mallplus.oms.service.IAdminDayStaticsService;
import com.zscat.mallplus.oms.service.IOmsOrderItemService;
import com.zscat.mallplus.oms.service.IOmsOrderItemTicketService;
import com.zscat.mallplus.oms.service.IOmsOrderService;
import com.zscat.mallplus.oms.vo.OrderParam;
import com.zscat.mallplus.pms.entity.PmsProduct;
import com.zscat.mallplus.pms.service.IPmsProductService;
import com.zscat.mallplus.sms.entity.SmsFlashPromotion;
import com.zscat.mallplus.sms.entity.SmsFlashPromotionProductRelation;
import com.zscat.mallplus.sms.entity.SmsFlashPromotionSession;
import com.zscat.mallplus.sms.entity.SmsGroup;
import com.zscat.mallplus.sms.mapper.SmsGroupMemberMapper;
import com.zscat.mallplus.sms.mapper.SmsGroupRecordMapper;
import com.zscat.mallplus.sms.service.ISmsCouponHistoryService;
import com.zscat.mallplus.sms.service.ISmsCouponService;
import com.zscat.mallplus.sms.service.ISmsFlashPromotionProductRelationService;
import com.zscat.mallplus.sms.service.ISmsFlashPromotionService;
import com.zscat.mallplus.sms.service.ISmsFlashPromotionSessionService;
import com.zscat.mallplus.sms.service.ISmsGroupService;
import com.zscat.mallplus.sys.entity.AdminDayStatics;
import com.zscat.mallplus.ums.entity.UmsIntegrationChangeHistory;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.mapper.UmsIntegrationChangeHistoryMapper;
import com.zscat.mallplus.ums.mapper.UmsMemberMapper;
import com.zscat.mallplus.ums.service.IFenxiaoMemberTotalService;
import com.zscat.mallplus.ums.service.IUmsIntegrationChangeHistoryService;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.util.DateUtil;
import com.zscat.mallplus.util.StringUtils;
import com.zscat.mallplus.util.WxContentUtils;
import com.zscat.mallplus.utils.CommonResult;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
//@Api(tags = "CenterController", description = "个人中心")
//@RequestMapping("/api/center")
@RequestMapping("/centers")

public class CenterControllers {
	@Resource
	private IUmsMemberService memberService;
	@Resource
	private CenterService centerService;
	@Resource
	private CenterVerificationMapper verificationMapper;
	@Resource
	private ICenterJifenService centerJifenService;
	@Resource
	private IAdminDayStaticsService adminDayStaticsService;
	@Resource
	private FenxiaoUserRelateMapper fenxiaoUserRelateMapper;
	@Resource
	private IOmsOrderService orderService;
	@Resource
	private OmsOrderItemMapper orderItemMapper;
	@Resource
	private UmsMemberMapper memberMapper;
	@Resource
	private OmsOrderMapper orderMapper;
	@Resource
	private IUmsIntegrationChangeHistoryService integrationChangeHistoryService;
	@Resource
	private ICenterItemService centerItemService;
	@Resource
	private UmsIntegrationChangeHistoryMapper integrationChangeHistoryMapper;
	@Resource
	private ISmsGroupService groupService;
	@Resource
	private ISmsFlashPromotionService flashPromotionService;
	@Resource
	private ISmsFlashPromotionProductRelationService flashPromotionProductRelationService;
	@Resource
	private IPmsProductService productService;
	@Resource
	private ISmsFlashPromotionSessionService flashPromotionSessionService;
	@Resource
	private CenterOrderMapper centerOrderMapper;
	@Resource
	private ISmsCouponService couponService;
	@Resource
	private ISmsCouponHistoryService ISmsCouponHistoryService;
	@Resource
	private ISmsCouponService ISmsCouponService;
	@Resource
	private IOmsOrderItemTicketService orderItemTicketService;
	@Resource
	private ISysStoreService storeService;
	@Resource
	private SmsGroupRecordMapper groupRecordMapper;
	@Resource
	private SmsGroupMemberMapper groupMemberMapper;
	@Resource
	private ICenterOrderService centerOrderService;
	@Autowired
	private IOmsOrderItemService orderItemService;
	@Autowired
	private IFenxiaoMemberTotalService fenxiaoMemberTotalService;
	@Autowired
	private FenxiaoRecordsMapper fenxiaoRecordsMapper;

	/**
	 * 添加邀请
	 * 
	 * @param centerInviteRecords
	 * @return
	 */
	@PostMapping("/invite/add")
	public Object addInviteData(@RequestBody CenterInviteRecords centerInviteRecords) {
		CenterInviteRecords inviteRecords = centerService.getInviteRecordsByInviteId(centerInviteRecords.getInviteId());
		if (inviteRecords != null) {
			return new CommonResult().failed("已绑定推荐人");
		}
		// 被邀请人（注册用户）
		UmsMember umsMember = memberService.getById(centerInviteRecords.getInviteId());
		// 邀请人
		UmsMember member = memberService.getById(centerInviteRecords.getUserId());
		if (member == null) {
			return new CommonResult().failed("邀请人不存在");
		} else {
			umsMember.setInvite(member.getId());
			umsMember.setInviteName(member.getNickname());
			memberService.updateById(umsMember);
		}
		// FenxiaoUserRelate
		FenxiaoUserRelate selectOne = fenxiaoUserRelateMapper
				.selectOne(new QueryWrapper<FenxiaoUserRelate>().eq("invite_id", umsMember.getId()));
		if (null == selectOne) {
			FenxiaoUserRelate entity = new FenxiaoUserRelate();
			entity.setMemberId(centerInviteRecords.getUserId().intValue());
			entity.setInviteId(centerInviteRecords.getInviteId().intValue());
			entity.setCreateTime(new Date());
			fenxiaoUserRelateMapper.insert(entity);
		}
		// FenxiaoMemberTotal
		FenxiaoMemberTotal fenxiaoMemberTotal = fenxiaoMemberTotalService
				.getOne(new QueryWrapper<FenxiaoMemberTotal>().eq("id", umsMember.getId()));
		if (null == fenxiaoMemberTotal) {
			fenxiaoMemberTotal = new FenxiaoMemberTotal();
			fenxiaoMemberTotal.setId(member.getId());
			fenxiaoMemberTotal.setName(member.getNickname());
			fenxiaoMemberTotal.setCurrentAmout(BigDecimal.ZERO);
			fenxiaoMemberTotal.setFrezzAmount(BigDecimal.ZERO);
			fenxiaoMemberTotal.setTotalAmount(BigDecimal.ZERO);
			fenxiaoMemberTotalService.save(fenxiaoMemberTotal);
		}
		// 插入积分日志表
		UmsIntegrationChangeHistory historyChange = new UmsIntegrationChangeHistory(member.getId(), new Date(),
				AllEnum.ChangeType.Add.code(), 100, member.getUsername(), "注册添加积分",
				AllEnum.ChangeSource.register.code());
		integrationChangeHistoryMapper.insert(historyChange);
		// 修改会员积分
		member.setIntegration(member.getIntegration() + 100);
		memberService.updateById(member);
		// 生成积分明细
		CenterItem centerItem = new CenterItem();
		centerItem.setUserId(member.getId());
		centerItem.setName("注册添加积分");
		centerItem.setTime(new Date());
		centerItem.setStoreId(member.getStoreId());
		centerItem.setType(1);
		centerItem.setIncome(100.0d);
		centerItemService.insertCenterItem(centerItem);

		CenterJifen centerJifen = centerJifenService.selectCenterJifenById(member.getId());
		if (null != centerJifen) {
			centerJifen.setScore(centerJifen.getScore() + 100);
			centerJifenService.updateById(centerJifen);
		}
		return new CommonResult().success(centerService.addInviteData(centerInviteRecords));
	}

	/**
	 * 我的邀请
	 * 
	 * @param userId
	 * @return
	 */
	// @IgnoreAuth
	// @SysLog(MODULE = "center", REMARK = "我的邀请")
	@GetMapping("/invite/{userId}")
	public Object getInviteData(@PathVariable("userId") Long userId) {
		return new CommonResult().success(centerService.getInviteData(userId));
	}

	/**
	 * 我的推广
	 * 
	 * @param userId
	 * @return
	 */
	// @IgnoreAuth
	// @SysLog(MODULE = "center", REMARK = "我的推广")
	@GetMapping("/extend/{userId}")
	public Object getExtendData(@PathVariable("userId") Long userId) {
		return new CommonResult().success(centerService.getExtendData(userId));
	}

	// TODO
	/**
	 * 我的消息
	 * 
	 * @param userId
	 * @return
	 */
	@IgnoreAuth
	// @SysLog(MODULE = "center", REMARK = "我的推广")
	@GetMapping("/message/{userId}")
	public Object getMessageData(@PathVariable("userId") Long userId) {
		return new CommonResult().success(centerService.getMessageData(userId));
	}

	// /**
	// * 添加系统消息
	// *
	// * @param adminSysNotice
	// * @return
	// */
	// @PostMapping("/message/adminSysNotice/add")
	// public Object addAdminSysNotice(@RequestBody AdminSysNotice adminSysNotice) {
	// return new
	// CommonResult().success(centerService.addAdminSysNotice(adminSysNotice));
	// }

	/**
	 * 系统消息列表addAdminSysNotice
	 * 
	 * @param userId
	 * @return
	 */
	@GetMapping("/message/adminSysNotice/user/{userId}")
	public Object getAdminSysNoticeList(@PathVariable("userId") Long userId) {
		return new CommonResult().success(centerService.getAdminSysNoticeList(userId));
	}

	/**
	 * 系统消息详情
	 * 
	 * @param noticeId
	 * @return
	 */
	@GetMapping("/message/adminSysNotice/{noticeId}")
	public Object getAdminSysNotice(@PathVariable("noticeId") Long noticeId) {
		return new CommonResult().success(centerService.getAdminSysNotice(noticeId));
	}

	/**
	 * 实名认证
	 * 
	 * @param userId
	 * @return
	 */
	// @IgnoreAuth
	// @SysLog(MODULE = "center", REMARK = "实名认证")
	// @PostMapping("/identification/add")
	// public Object addIdentification(@RequestBody CenterIdentification
	// centerIdentification) {
	// //审核通过
	// if() {
	// return new CommonResult().failed("审核通过不可修改");
	// }
	// return new
	// CommonResult().success(centerService.addIdentification(centerIdentification));
	// }

	/**
	 * 获取实名认证信息
	 * 
	 * @param
	 * @return
	 */
	// @IgnoreAuth
	// @SysLog(MODULE = "center", REMARK = "实名认证")
	// @GetMapping("/identification/{userId}")
	// public Object getIdentificationData(@PathVariable("userId") Long userId) {
	// return new
	// CommonResult().success(centerService.getIdentificationData(userId));
	// }

	/*
	 * 获取所有个人信息-喜欢的分类
	 * 
	 * @return
	 */
	@GetMapping("/memberInfo/getMemberTags")
	public Object getMemberTagsData() {
		return new CommonResult().success(centerService.getMemberTagsData());
	}

	/**
	 * 修改个人信息
	 * 
	 * @param memberInfoVo
	 * @return
	 */
	// @IgnoreAuth
	// @SysLog(MODULE = "center", REMARK = "修改个人信息")
	@PostMapping("/memberInfo/update")
	public Object updateMemberInfo(@RequestBody MemberInfoVo memberInfoVo) {
		if (memberInfoVo.getUserId() == null) {
			return new CommonResult().failed("用户信息异常");
		}
		return new CommonResult().success(centerService.updateMemberInfo(memberInfoVo));
	}

	/**
	 * 获取个人信息
	 * 
	 * @param userId
	 * @return
	 */
	// @IgnoreAuth
	// @SysLog(MODULE = "center", REMARK = "获取个人信息")
	@GetMapping("/memberInfo/{userId}")
	public Object getMemberInfoData(@PathVariable("userId") Long userId) {
		return new CommonResult().success(centerService.getMemberInfoData(userId));
	}

	// 新增核销码（支付成功后回调）
	/**
	 * @param orderSn 订单号
	 * @return
	 */
	@GetMapping("/verification/add")
	public Object addVerification(@RequestParam(required = true, name = "orderSn") String orderSn) {
		// 订单是否已生成核销码
		Integer orderCount = verificationMapper
				.selectCount(new QueryWrapper<CenterVerification>().eq("order_sn", orderSn));
		if (orderCount.compareTo(0) > 0) {
			return new CommonResult().success();
		}
		return new CommonResult().success(centerService.addVerification(orderSn));
	}

	/**
	 * 订单详情页
	 * 
	 * @param verification
	 * @return
	 */
	@GetMapping("/verification/list")
	public Object listVerification(CenterVerification verification) {
		Map<String, Object> map = new HashMap<String, Object>();
		UmsMember currentMember = UserUtils.getCurrentMember();
		if (null == currentMember) {
			return new CommonResult().failed("获取员工信息异常");
		}
		List<CenterVerification> selectList = verificationMapper.selectList(
				new QueryWrapper<CenterVerification>().eq("verification_code", verification.getVerificationCode()).or()
						.eq("order_sn", verification.getOrderSn()));

		map.put("centerVerification", selectList);
		OmsOrderItem item = null;
		OmsOrderItemTicket orderItem = null;
		if (StringUtils.isEmpty(verification.getOrderSn())) {
//			orderItem = orderItemMapper.selectOne(
//					new QueryWrapper<OmsOrderItem>().like("coupon_code", verification.getVerificationCode()));
			orderItem = orderItemTicketService.getOne(
					new QueryWrapper<OmsOrderItemTicket>().eq("coupon_code", verification.getVerificationCode()));
			if (null == orderItem) {
				return new CommonResult().failed("核销码有误");
			} else {
				item = orderItemMapper
						.selectOne(new QueryWrapper<OmsOrderItem>().eq("order_id", orderItem.getOrderId()));
			}
		} else {
			item = orderItemMapper
					.selectOne(new QueryWrapper<OmsOrderItem>().eq("order_sn", verification.getOrderSn()));
			orderItem = orderItemTicketService
					.getOne(new QueryWrapper<OmsOrderItemTicket>().eq("order_id", item.getOrderId()));
			if (null == orderItem) {
				return new CommonResult().failed("订单编号有误");
			}
		}
		map.put("orderItem", item);

		OmsOrder order = orderMapper.selectOne(new QueryWrapper<OmsOrder>().eq("id", orderItem.getOrderId()));
		if (null == order) {
			return new CommonResult().failed("订单有误");
		}
		map.put("order", order);
		UmsMember member = memberMapper.selectById(order.getMemberId());
		if (null == member) {
			return new CommonResult().failed("获取客戶信息异常");
		}
		map.put("member", member);

		return new CommonResult().success(map);
	}

	/**
	 * 核销码列表
	 * 
	 * @param verification
	 * @return
	 */
	@GetMapping("/verification/lists")
	public Object CenterVerification(CenterVerification verification) {
		return new CommonResult().success(centerService.listVerification(verification));
	}

	/**
	 * 核销扫码
	 * 
	 * @param verificationCode 核销码
	 * @return
	 */
	@GetMapping("/verification/scan")
	public Object scanVerificationCode(
			@RequestParam(required = true, name = "verificationCode") String verificationCode,Long userId) {
		UmsMember member = memberService.getById(userId);
		CenterVerification verification = verificationMapper.selectOne(new QueryWrapper<CenterVerification>()
				.eq("verification_code", verificationCode).eq("store_id",member.getStoreId()));
		if (verification == null) {
			return new CommonResult().failed("该码有误");
		} else {
			if (verification.getVerification() == 1) {
				return new CommonResult().failed("该码已核销");
			}
		}
		verification.setOperateId(member.getId());
		verification.setOperateName(member.getNickname());

		OmsOrderItemTicket ticket = orderItemTicketService
				.getOne(new QueryWrapper<OmsOrderItemTicket>().eq("coupon_code", verificationCode));
		if (ticket == null) {
			return new CommonResult().failed("该码有误");
		} else {
			if (ticket.getStatus() == 1) {
				return new CommonResult().failed("该码已核销");
			}
		}
		ticket.setStatus(1);
		orderItemTicketService.updateById(ticket);

		if (centerService.scanVerificationCode(verification)) {
			List<OmsOrderItemTicket> list = orderItemTicketService
					.list(new QueryWrapper<OmsOrderItemTicket>().eq("order_id", ticket.getOrderId()).eq("status", 0));
			if (list == null || list.size() == 0) {
				OmsOrder entity = new OmsOrder();
				entity.setId(ticket.getOrderId());
				entity.setStatus(3);
				entity.setConfirmStatus(1);
				entity.setReceiveTime(new Date());
				orderService.updateById(entity);
			}
		}
		return new CommonResult().success(true);
	}

	/**
	 * 批量核销扫码
	 * 
	 * @param orderSn           订单号
	 * @param verificationCount 核销数量
	 * @return
	 */
	@GetMapping("/verification/batchScan")
	public Object batchScanVerification(@RequestParam(required = true, name = "orderSn") String orderSn,
			@RequestParam(required = true, name = "verificationCount") Integer verificationCount,Long userId) {
		UmsMember member = memberService.getById(userId);
		CenterVerification centerVerification = new CenterVerification();
		centerVerification.setVerification(0);
		centerVerification.setOrderSn(orderSn);
		centerVerification.setStoreId(member.getStoreId());
		List<CenterVerification> verificationList = verificationMapper.selectCenterVerificationList(centerVerification);
		if (verificationList == null || verificationList.isEmpty()) {
			return new CommonResult().failed("核销码已全部用完");
		}
		if (verificationList.size() < verificationCount) {
			return new CommonResult().failed("核销码数量已超出");
		}

		return new CommonResult().success(centerService.batchScanVerification(verificationList, verificationCount));
	}

	/**
	 * 系统通知获取会员详情
	 * 
	 * @param noticeId
	 * @return
	 */
	@GetMapping("/message/adminSysNotice/getMemberList/{noticeId}")
	public Object getMemberList(@PathVariable(name = "noticeId") Long noticeId) {
		return new CommonResult().success(centerService.getAdminSysNoticeMemberList(noticeId));
	}

	/**
	 * 获取所有会员
	 * 
	 * @return
	 */
	@GetMapping("/message/adminSysNotice/getAllMemberList")
	public Object getAllMemberList() {
		return new CommonResult().success(centerService.getAllMemberList());
	}

	/**
	 * 新增系统通知
	 * 
	 * @param userIds
	 * @param noticeId
	 * @return
	 */
	@GetMapping("/message/adminSysNotice/add")
	public Object addCenterUserSysNotice(@RequestParam(name = "userIds") Long[] userIds,
			@RequestParam(name = "noticeId") Long noticeId) {
		return new CommonResult().success(centerService.addCenterUserSysNotice(userIds, noticeId));
	}

	@GetMapping(value = "/adminStatic/list")
	public Object getAdminAllStaticsByPage(AdminDayStatics entity,
			@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
		try {
			return new CommonResult().success(adminDayStaticsService.page(new Page<AdminDayStatics>(pageNum, pageSize),
					new QueryWrapper<>(entity).select(
							"store_id,store_name,SUM(IFNULL(goods_count,0)) AS allGoodsCount,SUM(IFNULL(article_count,0)) AS allArticleCount,SUM(IFNULL(pay_order_count,0)) AS allPayOrderCount,SUM(IFNULL(pay_amount,0)) AS allPayAmount,SUM(IFNULL(not_pay_order_count,0)) AS allNotPayOrderCount,SUM(IFNULL(not_pay_amount,0)) AS allNotPayAmount")
							.groupBy("store_id").orderByDesc("create_time")));
		} catch (Exception e) {
			log.error("根据条件查询所有商户统计列表：%s", e.getMessage(), e);
		}
		return new CommonResult().failed();
	}

	/**
	 * 添加科普评论
	 * 
	 * @param subjectComment
	 * @return
	 */
	@PostMapping(value = "addSubjectComment")
	public Object addSubjectComment(@RequestBody CmsSubjectComment subjectComment) {
		Object object = WxContentUtils.Wxcontent(subjectComment.getContent());
		if (object != null) {
			return object;
		}
		return centerService.saveSubjectComment(subjectComment);
	}

	/**
	 * 拼团商品列表
	 * 
	 * @param subjectComment
	 * @return
	 */
	@GetMapping(value = "/group/productList")
	public Object groupProductList(SmsGroup entity) {
		try {
			List<SmsGroup> list = groupService.list(new QueryWrapper<SmsGroup>(entity).le("start_time", new Date())
					.ge("end_time", new Date()).orderByDesc("id"));
			ListIterator<SmsGroup> listIterator = list.listIterator();
			while (listIterator.hasNext()) {
				SmsGroup smsGroup = listIterator.next();
				PmsProduct product = productService
						.getOne(new QueryWrapper<PmsProduct>().eq("id", smsGroup.getGoodsId()).eq("publish_status", 1));
				if (null != product) {
					smsGroup.setOriginalPrice(product.getOriginalPrice());
					smsGroup.setProductImg(product.getPic());
					smsGroup.setProductSubTitle(product.getSubTitle());
					smsGroup.setGroupProductCount(centerOrderMapper.groupProductCount(smsGroup.getId()));
				} else {
					listIterator.remove();
				}
			}
			return new CommonResult().success(list);
		} catch (Exception e) {
			log.error("根据条件查询所有列表：%s", e.getMessage(), e);
		}
		return new CommonResult().failed();
	}

	/**
	 * 秒杀活动时间段列表
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/flashPromotion/sessionList")
	public Object sessionList(SmsFlashPromotionSession entity) {
		List<SmsFlashPromotionSession> flashPromotionSessionList = flashPromotionSessionService
				.list(new QueryWrapper<SmsFlashPromotionSession>(entity).eq("status", 1).orderByAsc("start_time"));

		for (SmsFlashPromotionSession smsFlashPromotionSession : flashPromotionSessionList) {
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
			TimeZone.getTimeZone("GMT+8");
			long currentTime = 0l;
			try {
				currentTime = sdf.parse(sdf.format(new Date())).getTime();
				long startTime = sdf.parse(sdf.format(smsFlashPromotionSession.getStartTime())).getTime();
				long endTime = sdf.parse(sdf.format(smsFlashPromotionSession.getEndTime())).getTime();
				if (currentTime > endTime) {
					smsFlashPromotionSession.setState("1");// 过期
				} else if (startTime <= currentTime && currentTime <= endTime) {
					smsFlashPromotionSession.setState("2");// 进行
				} else {
					smsFlashPromotionSession.setState("3");// 未开始
				}
			} catch (Exception e) {
				log.error("当前秒杀商品列表flashPromotionProductList%s", e.getMessage(), e);
			}
		}
		return new CommonResult().success(flashPromotionSessionList);
	}

	/**
	 * 秒杀活动时间段商品列表
	 * 
	 * @param flashPromotionSessionId 时间段编号
	 * @return
	 */
	@GetMapping(value = "/flashPromotion/session/productList")
	public Object productList(SmsFlashPromotionProductRelation entity) {
		List<SmsFlashPromotion> flashPromotionList = flashPromotionService
				.list(new QueryWrapper<SmsFlashPromotion>().eq("store_id", entity.getStoreId()).eq("status", 1)
						.gt("end_date", DateUtil.dateToStr(new Date(), "yyyy-MM-dd")));
		if (flashPromotionList.isEmpty()) {
			return new CommonResult().success(null);
		}
		List<SmsFlashPromotionProductRelation> productList = new ArrayList<SmsFlashPromotionProductRelation>();
		for (SmsFlashPromotion smsFlashPromotion : flashPromotionList) {
			entity.setFlashPromotionId(smsFlashPromotion.getId());
			List<SmsFlashPromotionProductRelation> flashPromotionProductRelationList = flashPromotionProductRelationService
					.list(new QueryWrapper<SmsFlashPromotionProductRelation>(entity).orderByAsc("sort"));
			ListIterator<SmsFlashPromotionProductRelation> listIterator = flashPromotionProductRelationList
					.listIterator();
			while (listIterator.hasNext()) {
				SmsFlashPromotionProductRelation smsFlashPromotionProductRelation = listIterator.next();
				PmsProduct product = productService.getOne(new QueryWrapper<PmsProduct>()
						.eq("id", smsFlashPromotionProductRelation.getProductId()).eq("publish_status", 1));
				if (null != product) {
					smsFlashPromotionProductRelation.setProductId(product.getId());
					smsFlashPromotionProductRelation.setProductImg(product.getPic());
					smsFlashPromotionProductRelation.setProductName(product.getName());
					smsFlashPromotionProductRelation.setProductSubTitle(product.getSubTitle());
					smsFlashPromotionProductRelation.setProductPrice(product.getPrice());
					smsFlashPromotionProductRelation.setOriginalPrice(product.getOriginalPrice());
					smsFlashPromotionProductRelation
							.setFlashPromotionProductCount(orderItemService.countProductQuantity(null,
									OrderType.SKILL.code(), smsFlashPromotionProductRelation.getId()));
				} else {
					listIterator.remove();
				}
			}
			productList.addAll(flashPromotionProductRelationList);
		}
		return new CommonResult().success(productList);
	}

	/**
	 * 当前秒杀商品列表
	 * 
	 * @param subjectComment
	 * @return
	 */
	@GetMapping(value = "/flashPromotion/productList")
	public Object flashPromotionProductList(@RequestParam Integer storeId) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<SmsFlashPromotion> flashPromotionList = flashPromotionService.list(new QueryWrapper<SmsFlashPromotion>()
				.eq("store_id", storeId).eq("status", 1).gt("end_date", DateUtil.dateToStr(new Date(), "yyyy-MM-dd")));
		if (flashPromotionList.isEmpty()) {
			return new CommonResult().success(null);
		}
		// 当前时间段
		List<SmsFlashPromotionSession> flashPromotionSessionList = flashPromotionSessionService
				.list(new QueryWrapper<SmsFlashPromotionSession>().eq("status", 1).eq("store_id", storeId)
						.orderByAsc("start_time"));
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		SmsFlashPromotionSession currentFlashPromotionSession = null;
		try {
			long currentTime = sdf.parse(sdf.format(new Date())).getTime();
			for (int i = 0; i < flashPromotionSessionList.size(); i++) {
				long startTime = sdf.parse(sdf.format(flashPromotionSessionList.get(i).getStartTime())).getTime();
				long endTime = sdf.parse(sdf.format(flashPromotionSessionList.get(i).getEndTime())).getTime();
				if (startTime <= currentTime && currentTime <= endTime) {
					currentFlashPromotionSession = flashPromotionSessionList.get(i);
					break;
				} else if (currentTime <= startTime) {
					// 取下一个时间段
					currentFlashPromotionSession = flashPromotionSessionList.get(i);
					break;
				}
			}
		} catch (Exception e) {
			log.error("当前秒杀商品列表flashPromotionProductList%s", e.getMessage(), e);
		}
		if (null == currentFlashPromotionSession) {
			return new CommonResult().failed("当前时间段未设置");
		}
		map.put("flashPromotionSession", currentFlashPromotionSession);
		// 商品
		List<SmsFlashPromotionProductRelation> productList = new ArrayList<SmsFlashPromotionProductRelation>();
		for (SmsFlashPromotion smsFlashPromotion : flashPromotionList) {
			List<SmsFlashPromotionProductRelation> flashPromotionProductRelationList = flashPromotionProductRelationService
					.list(new QueryWrapper<SmsFlashPromotionProductRelation>()
							.eq("flash_promotion_id", smsFlashPromotion.getId())
							.eq("flash_promotion_session_id", currentFlashPromotionSession.getId()).orderByAsc("sort"));
			for (SmsFlashPromotionProductRelation smsFlashPromotionProductRelation : flashPromotionProductRelationList) {
				PmsProduct product = productService.getOne(new QueryWrapper<PmsProduct>()
						.eq("id", smsFlashPromotionProductRelation.getProductId()).eq("publish_status", 1));
				if (null != product) {
					smsFlashPromotionProductRelation.setProductId(product.getId());
					smsFlashPromotionProductRelation.setProductImg(product.getPic());
					smsFlashPromotionProductRelation.setProductName(product.getName());
					smsFlashPromotionProductRelation.setProductSubTitle(product.getSubTitle());
					smsFlashPromotionProductRelation.setProductPrice(product.getPrice());
					smsFlashPromotionProductRelation.setOriginalPrice(product.getOriginalPrice());
					smsFlashPromotionProductRelation
							.setFlashPromotionProductCount(orderItemService.countProductQuantity(null,
									OrderType.SKILL.code(), smsFlashPromotionProductRelation.getId()));
					productList.add(smsFlashPromotionProductRelation);
				}
			}
		}
		map.put("productList", productList);
		return new CommonResult().success(map);
	}

	@ApiOperation("确认单信息封装")
	@PostMapping("/order/confirmOrderResult")
	public Object confirmOrderResult(@RequestBody OrderParam orderParam) {
		try {
			return new CommonResult().success(centerOrderService.confirmOrderResult(orderParam));
		} catch (ApiMallPlusException e) {
			return new CommonResult().failed(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@ApiOperation("提交拼团订单信息")
	@PostMapping("/order/submitGroupOrder")
	public Object submitGroupOrder(@RequestBody OrderParam orderParam) {
		try {
			return centerOrderService.submitGroupOrder(orderParam);
		} catch (ApiMallPlusException e) {
			return new CommonResult().failed(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@ApiOperation("提交秒杀订单信息")
	@PostMapping("/order/submitFlashPromotionOrder")
	public Object submitFlashPromotionOrder(@RequestBody OrderParam orderParam) {
		try {
			return centerOrderService.submitFlashPromotionOrder(orderParam);
		} catch (ApiMallPlusException e) {
			return new CommonResult().failed(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@ApiOperation("收益明细")
	@GetMapping("/memberInfo/incomeDetails")
	public Object incomeDetails(FenxiaoRecords fenxiaoRecords,
			@RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
			@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum) {
		try {
			UmsMember currentMember = memberService.getNewCurrentMember();
			if (null == currentMember) {
				return new CommonResult().failed("请先登录");
			}
			fenxiaoRecords.setMemberId(currentMember.getId());
			IPage<FenxiaoRecords> selectPage = fenxiaoRecordsMapper.selectPage(
					new Page<FenxiaoRecords>(pageNum, pageSize),
					new QueryWrapper<FenxiaoRecords>(fenxiaoRecords).orderByDesc("create_time"));
			List<IncomeDetails> incomeDetailsList = new ArrayList<IncomeDetails>();
			for (FenxiaoRecords records : selectPage.getRecords()) {
				IncomeDetails incomeDetails = new IncomeDetails();
				OmsOrder order = orderMapper.selectById(records.getOrderId());
				UmsMember member = memberService.getById(order.getMemberId());
				incomeDetails.setCreateTime(order.getCreateTime());
				incomeDetails.setFenxiaoType(records.getFenxiaoType());
				incomeDetails.setGoodsId(records.getGoodsId());
				incomeDetails.setId(records.getId());
				incomeDetails.setInviteId(records.getInviteId());
				incomeDetails.setLevel(records.getLevel());
				incomeDetails.setMemberId(member.getId());
				incomeDetails.setMemberUsername(member.getNickname());
				incomeDetails.setIcon(member.getIcon());
				incomeDetails.setMoney(records.getMoney());
				incomeDetails.setOrderId(records.getOrderId());
				incomeDetails.setPayAmount(order.getPayAmount());
				incomeDetails.setStatus(records.getStatus());
				incomeDetails.setType(records.getType());
				incomeDetailsList.add(incomeDetails);
			}
			IPage<IncomeDetails> page = new IPage<IncomeDetails>() {
				private static final long serialVersionUID = 1L;

				@Override
				public IPage<IncomeDetails> setTotal(long total) {
					// TODO Auto-generated method stub
					return null;
				}

				@Override
				public IPage<IncomeDetails> setSize(long size) {
					// TODO Auto-generated method stub
					return null;
				}

				@Override
				public IPage<IncomeDetails> setRecords(List<IncomeDetails> records) {
					// TODO Auto-generated method stub
					return null;
				}

				@Override
				public IPage<IncomeDetails> setCurrent(long current) {
					// TODO Auto-generated method stub
					return null;
				}

				@Override
				public long getTotal() {
					// TODO Auto-generated method stub
					return selectPage.getTotal();
				}

				@Override
				public long getSize() {
					// TODO Auto-generated method stub
					return selectPage.getSize();
				}

				@Override
				public List<IncomeDetails> getRecords() {
					// TODO Auto-generated method stub
					return incomeDetailsList;
				}

				@Override
				public long getCurrent() {
					// TODO Auto-generated method stub
					return selectPage.getCurrent();
				}
			};
			return page;
		} catch (ApiMallPlusException e) {
			return new CommonResult().failed(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
